import { Alert, CodeGroup, ContentByFramework } from "@/components/forMdx";

export const metadata = {
  description: "CoMaps are key-value objects that work like JavaScript objects. Best for structured data that needs type validation."
};

# CoMaps

CoMaps are key-value objects that work like JavaScript objects. You can access properties with dot notation and define typed fields that provide TypeScript safety. They're ideal for structured data that needs type validation.

## Creating CoMaps

CoMaps are typically defined with `co.map()` and specifying primitive fields using `z` (see [Defining schemas: CoValues](/docs/core-concepts/covalues/overview) for more details on primitive fields):

<CodeGroup>
```ts index.ts#Basic
```
</CodeGroup>

You can create either struct-like CoMaps with fixed fields (as above) or record-like CoMaps for key-value pairs:

<CodeGroup>
```ts index.ts#Records
```
</CodeGroup>

To instantiate a CoMap:

<CodeGroup>
```ts index.ts#Instantiation
```
</CodeGroup>

### Ownership

When creating CoMaps, you can specify ownership to control access:

<CodeGroup>
```ts index.ts#Ownership
```
</CodeGroup>

See [Groups as permission scopes](/docs/permissions-and-sharing/overview) for more information on how to use groups to control access to CoMaps.

## Reading from CoMaps

CoMaps can be accessed using familiar JavaScript object notation:

<CodeGroup>
```ts index.ts#Reading
```
</CodeGroup>

### Handling Optional Fields

Optional fields require checks before access:

<CodeGroup>
```ts index.ts#Optional
```
</CodeGroup>

### Recursive references

You can wrap references in getters. This allows you to defer evaluation until the property is accessed. This technique is particularly useful for defining circular references, including recursive (self-referencing) schemas, or mutually recursive schemas.

<CodeGroup>
```ts with-getters.ts#WithGetter
```
</CodeGroup>

When the recursive references involve more complex types, it is sometimes required to specify the getter return type:
<CodeGroup>
```ts with-getters.ts#WithTypedGetter
```
</CodeGroup>

### Partial

For convenience Jazz provies a dedicated API for making all the properties of a CoMap optional:

<CodeGroup>
```ts partial.ts
```
</CodeGroup>

### Pick

You can also pick specific fields from a CoMap:

<CodeGroup>
```ts pick.ts
```
</CodeGroup>

### Working with Record CoMaps

For record-type CoMaps, you can access values using bracket notation:

<CodeGroup>
```ts record.ts#BracketNotation
```
</CodeGroup>

## Updating CoMaps

To update a CoMap's properties, use the `$jazz.set` method:

<CodeGroup>
```ts index.ts#Update
```
</CodeGroup>

<Alert variant="info" className="flex gap-2 items-center my-4">
The `$jazz` namespace is available on all CoValues, and provides access to methods to modify and load CoValues,
as well as access common properties like `id` and `owner`.
</Alert>

When updating references to other CoValues, you can provide both the new CoValue or a JSON object from which the new CoValue will be created.
<CodeGroup>
```ts index.ts#ImplicitExplicit
```
</CodeGroup>

When providing a JSON object, Jazz will automatically create the CoValues for you.
To learn more about how permissions work in this case, refer to
[Ownership on implicit CoValue creation](/docs/permissions-and-sharing/cascading-permissions#ownership-on-implicit-covalue-creation).

### Type Safety

CoMaps are fully typed in TypeScript, giving you autocomplete and error checking:

<CodeGroup>
```ts index.ts#TypeSafety
```
</CodeGroup>

### Soft Deletion

Implementing a soft deletion pattern by using a `deleted` flag allows you to maintain data for potential recovery and auditing.

<CodeGroup>
```ts soft-deletions.ts
```
</CodeGroup>
When an object needs to be "deleted", instead of removing it from the system, the deleted flag is set to true. This gives us a property to omit it in the future.

### Deleting Properties

You can delete properties from CoMaps:

<CodeGroup>
```ts index.ts#DeleteProperties
```
</CodeGroup>

## Running migrations on CoMaps

Migrations are functions that run when a CoMap is loaded, allowing you to update existing data to match new schema versions. Use them when you need to modify the structure of CoMaps that already exist in your app. Unlike [Account migrations](/docs/core-concepts/schemas/accounts-and-migrations#when-migrations-run), CoMap migrations are not run when a CoMap is created.

**Note:** Migrations are run synchronously and cannot be run asynchronously.

Here's an example of a migration that adds the `priority` field to the `Task` CoMap:

<CodeGroup>
```ts index.ts#Migrations
```
</CodeGroup>

### Migration best practices

Design your schema changes to be compatible with existing data:
- **Add, don't change:** Only add new fields; avoid renaming or changing types of existing fields
- **Make new fields optional:** This prevents errors when loading older data
- **Use version fields:** Track schema versions to run migrations only when needed

### Migration & reader permissions

Migrations need write access to modify CoMaps. If some users only have read permissions, they can't run migrations on those CoMaps.

**Forward-compatible schemas** (where new fields are optional) handle this gracefully - users can still use the app even if migrations haven't run.

**Non-compatible changes** require handling both schema versions in your app code using discriminated unions.

When you can't guarantee all users can run migrations, handle multiple schema versions explicitly:

<CodeGroup>
```ts index.ts#ComplexMigrations
```
</CodeGroup>

## Best Practices

### Structuring Data

- Use struct-like CoMaps for entities with fixed, known properties
- Use record-like CoMaps for dynamic key-value collections
- Group related properties into nested CoMaps for better organization

### Common Patterns

#### Helper methods

You should define helper methods of CoValue schemas separately, in standalone functions:

<CodeGroup>
```ts helpers.ts
```
</CodeGroup>

#### Uniqueness

CoMaps are typically created with a CoValue ID that acts as an opaque UUID, by which you can then load them. However, there are situations where it is preferable to load CoMaps using a custom identifier:
- The CoMaps have user-generated identifiers, such as a slug
- The CoMaps have identifiers referring to equivalent data in an external system
- The CoMaps have human-readable & application-specific identifiers
  - If an application has CoValues used by every user, referring to it by a unique *well-known* name (eg, `"my-global-comap"`) can be more convenient than using a CoValue ID

Consider a scenario where one wants to identify a CoMap using some unique identifier that isn't the Jazz CoValue ID:

<CodeGroup>
```ts uniqueness.ts#FailLoading
```
</CodeGroup>

To make it possible to use human-readable identifiers Jazz lets you to define a `unique` property on CoMaps.

Then the CoValue ID is deterministically derived from the `unique` property and the owner of the CoMap.

<CodeGroup>
```ts uniqueness.ts#Create
```
</CodeGroup>

Now you can use `CoMap.loadUnique` to easily load the CoMap using the human-readable identifier:

<CodeGroup>
```ts uniqueness.ts#LoadUnique
```
</CodeGroup>

It's also possible to combine the create+load operation using `CoMap.upsertUnique`:

<CodeGroup>
```ts uniqueness.ts#UpsertUnique
```
</CodeGroup>

**Caveats:**

- The `unique` parameter acts as an *immutable* identifier - i.e. the same `unique` parameter in the same `Group` will always refer to the same CoValue.

  - To make dynamic renaming possible, you can create an indirection where a stable CoMap identified by a specific value of `unique` is simply a pointer to another CoMap with a normal, dynamic CoValue ID. This pointer can then be updated as desired by users with the corresponding permissions.

- This way of introducing identifiers allows for very fast lookup of individual CoMaps by identifier, but it doesn't let you enumerate all the CoMaps identified this way within a `Group`. If you also need enumeration, consider using a global `co.record()` that maps from identifier to a CoMap, which you then do lookups in (this requires at least a shallow load of the entire `co.record()`, but this should be fast for up to 10s of 1000s of entries)

#### Creating Set-like Collections

You can use CoRecords as a way to create set-like collections, by keying the CoRecord on the item's CoValue ID. You can then use static `Object` methods to iterate over the CoRecord, effectively allowing you to treat it as a set.

<CodeGroup>
  ```ts record.ts#RecordAsSet
  ```
</CodeGroup>

You can choose a loading strategy for the CoRecord. Use $each when you need all item properties to be immediately available. In general, it is enough to shallowly load a CoRecord to access its keys, and then load the values of those keys as needed (for example, by passing the keys as strings to a child component).

<CodeGroup>
  ```ts record.ts#DeeplyLoadingKeys
  ```
</CodeGroup>
